#include "CApp.h"
#include <iostream>

using namespace std;

CApp::CApp() {
	Surf_Display = NULL;
	Surf_Test = NULL;
	Renderer = NULL;
	Texture = NULL;

	Running = true;
}
 
int CApp::OnExecute() {
	if(OnInit() == false)
		return -1;

	SDL_Event Event;

	while(Running) {
		while(SDL_PollEvent(&Event)) {
			OnEvent(&Event);
		}

		OnLoop();

		OnRender();
	}

	OnCleanup();

    return 0;
}

bool CApp::OnInit() {
	if(SDL_Init(SDL_INIT_EVERYTHING) < 0)
	{
		return false;
	}

	Surf_Display = SDL_CreateWindow("Game Window", SDL_WINDOWPOS_UNDEFINED, SDL_WINDOWPOS_UNDEFINED,
		640, 480, SDL_WINDOW_RESIZABLE  | SDL_WINDOW_OPENGL);

	if(Surf_Display == NULL) {
		return false;
	}

	Renderer = SDL_CreateRenderer(Surf_Display, -1, SDL_RENDERER_ACCELERATED);

	if(Renderer == NULL) {
		return false;
	}

	if((Surf_Test = SDL_LoadBMP("../fdsf.bmp")) == NULL) {
		return false;
	}

	if(Surf_Test == NULL) {
		return false;
	}

	Texture = SDL_CreateTextureFromSurface(Renderer, Surf_Test);

	return true;
}

void CApp::OnEvent(SDL_Event* Event) {
	CEvent::OnEvent(Event);
}

void CApp::OnLoop() {

}

void CApp::OnRender() {
	// CSurface::OnDraw(SDL_GetWindowSurface(Surf_Display), Surf_Test, 0, 0);

	SDL_RenderClear(Renderer);

	SDL_RenderCopy(Renderer, Texture, NULL, NULL);

	SDL_RenderPresent(Renderer);
	
}

void CApp::OnCleanup() {
	if(Surf_Test) {
		SDL_FreeSurface(Surf_Test);
	}

	if(Texture) {
		SDL_DestroyTexture(Texture);
	}

	if(Renderer) {
		SDL_DestroyRenderer(Renderer);
	}

	if(Surf_Display) {
		SDL_DestroyWindow(Surf_Display);
	}

	SDL_Quit();
}

void CApp::OnExit() {
	Running = false;
}